package cn.stylefeng.roses.seata.demo.account.modular.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.seata.demo.account.modular.service.AccountTblService;
import cn.stylefeng.roses.seata.demo.account.modular.service.TccUpdateAccountService;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * TCC方式实现更新用户
 *
 * @author fengshuonan
 * @date 2021/10/13 21:36
 */
@Service
public class TccUpdateAccountServiceImpl implements TccUpdateAccountService {

    @Resource
    private AccountTblService accountTblService;

    @Override
    public boolean updateAccountTry(String userId, int subMoney) {
        // 冻结账户余额

        // 模拟出现异常
        if (RandomUtil.randomBoolean()) {
            throw new ServiceException("account", "500", "account异常");
        }

        return true;
    }

    @Override
    public boolean updateAccountConfirm(BusinessActionContext context) {

        String userId = (String) context.getActionContext("userId");
        Integer subMoney = (Integer) context.getActionContext("subMoney");

        // 真正扣减余额
        this.accountTblService.updateMoney(userId, subMoney);

        return true;
    }

    @Override
    public boolean updateAccountCancel(BusinessActionContext context) {

        // 解除冻结账户余额

        return true;
    }

}